import { apiGet, apiPost, apiDelete, withAuth } from "@/lib/api/client";

export interface CreateSessionReq {
  personaId: string;
  skill: string;
}

export interface CreateSessionRes {
  sessionId: string;
  persona: {
    id: string;
    name: string;
    displayName: string;
    voiceId?: string | null;
    language: string;
    skills: string[];
    avatar?: string | null;
  };
  createdAt: string; // Beijing ISO
}

export async function createSession(payload: CreateSessionReq, signal?: AbortSignal) {
  return apiPost<CreateSessionRes>("/sessions", payload, { signal });
}

export interface SessionDetail {
  id: string;
  personaId: string;
  title?: string | null;
  skill?: string | null;
  personaSnapshot?: any;
  createdAt: string;
  updatedAt: string;
}

export async function getSessionById(sessionId: string, signal?: AbortSignal) {
  return apiGet<SessionDetail>(`/sessions/${sessionId}`, withAuth({ signal }));
}

export interface SessionsListRes {
  items: SessionDetail[];
  total: number;
  page: number;
  pageSize: number;
}

export async function getSessions(params?: { page?: number; pageSize?: number; order?: 'asc' | 'desc' }, signal?: AbortSignal) {
  const q = new URLSearchParams();
  if (params?.page) q.set('page', String(params.page));
  if (params?.pageSize) q.set('pageSize', String(params.pageSize));
  if (params?.order) q.set('order', params.order);
  const qs = q.toString();
  const path = `/sessions${qs ? `?${qs}` : ''}`;
  return apiGet<SessionsListRes>(path, withAuth({ signal }));
}

export interface DeleteSessionRes {
  success: boolean;
  message: string;
}

export async function deleteSession(sessionId: string, signal?: AbortSignal) {
  return apiDelete<DeleteSessionRes>(`/sessions/${sessionId}`, withAuth({ signal }));
}